<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    
    <!-- PWA支持 -->
    <link rel="manifest" href="manifest.json">
    <meta name="theme-color" content="#2c3e50">
    <link rel="apple-touch-icon" href="icon-192.png">
    <title>锻造规划计算器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f5;
            min-height: 100vh;
            padding: 20px;
            color: #333;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 20px rgba(0,0,0,0.08);
            overflow: hidden;
            border: 1px solid #e0e0e0;
        }
        
        .header {
            background: #2c3e50;
            color: white;
            padding: 40px 20px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 24px;
            margin-bottom: 10px;
        }
        
        .header p {
            opacity: 0.9;
            font-size: 14px;
        }
        
        .content {
            padding: 30px 20px;
        }
        
        .input-group {
            margin-bottom: 25px;
        }
        
        .input-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }
        
        .input-group input {
            width: 100%;
            padding: 16px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            transition: all 0.2s ease;
            background: #fafafa;
        }
        
        .input-group input:focus,
        .input-group select:focus {
            outline: none;
            border-color: #3498db;
            background: white;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }
        
        .input-group select {
            width: 100%;
            padding: 16px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            transition: all 0.2s ease;
            background: #fafafa;
            cursor: pointer;
        }
        
        .steps-container {
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 24px;
            margin-bottom: 25px;
            background: #fafafa;
        }
        
        .step-item {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 16px;
            border: 1px solid #e0e0e0;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }
        
        .step-item:last-child {
            margin-bottom: 0;
        }
        
        .step-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .step-title {
            font-weight: 600;
            color: #333;
        }
        
        .remove-step {
            background: #e74c3c;
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 12px;
            font-size: 12px;
            cursor: pointer;
            transition: background 0.2s ease;
        }
        
        .remove-step:hover {
            background: #c0392b;
        }
        
        .step-inputs {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
        }
        
        .btn {
            background: #3498db;
            color: white;
            border: none;
            border-radius: 8px;
            padding: 16px 30px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            width: 100%;
            margin-bottom: 12px;
        }
        
        .btn:hover {
            background: #2980b9;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
        }
        
        .btn-secondary {
            background: #95a5a6;
        }
        
        .btn-secondary:hover {
            background: #7f8c8d;
        }
        
        .results {
            background: white;
            border-radius: 8px;
            padding: 24px;
            margin-top: 24px;
            display: none;
            border: 1px solid #e0e0e0;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        .results.show {
            display: block;
        }
        
        .result-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }
        
        .result-table th,
        .result-table td {
            padding: 10px;
            text-align: center;
            border-bottom: 1px solid #dee2e6;
        }
        
        .result-table th {
            background: #34495e;
            color: white;
            font-weight: 500;
        }
        
        .success {
            color: #27ae60;
            font-weight: 500;
            background: #d5f4e6;
            padding: 12px 16px;
            border-radius: 6px;
            border-left: 4px solid #27ae60;
        }
        
        .error {
            color: #e74c3c;
            font-weight: 500;
            background: #fdf2f2;
            padding: 12px 16px;
            border-radius: 6px;
            border-left: 4px solid #e74c3c;
        }
        
        .plan {
            background: #f8f9fa;
            border-left: 4px solid #3498db;
            padding: 16px;
            margin: 16px 0;
            border-radius: 6px;
        }
        
        @media (max-width: 768px) {
            .container {
                max-width: 100%;
                margin: 5px;
                border-radius: 8px;
            }
            
            .header h1 {
                font-size: 18px;
                margin-bottom: 8px;
            }
            
            .header p {
                font-size: 14px;
                margin: 0;
            }
            
            .content {
                padding: 15px 10px;
            }
            
            .input-group {
                margin-bottom: 20px;
            }
            
            .input-group label {
                font-size: 16px;
                margin-bottom: 8px;
            }
            
            /* 原始钢锭参数在手机上改为单列布局 */
            .input-group > div[style*="grid-template-columns"] {
                grid-template-columns: 1fr !important;
                gap: 8px !important;
            }
            
            .step-inputs {
                grid-template-columns: 1fr;
                gap: 8px;
            }
            
            /* 可视化模式移动端优化 */
            #visualMode {
                margin: 0 -10px;
            }
            
            #visualMode > div {
                border-radius: 0;
                padding: 15px 10px;
            }
            
            #visualMode .visual-layout {
                flex-direction: column !important;
                height: auto !important;
                gap: 15px !important;
            }
            
            #visualMode .canvas-area {
                flex: none !important;
                width: 100% !important;
            }
            
            #visualMode .params-area {
                flex: none !important;
                width: 100% !important;
                min-width: auto !important;
                max-width: none !important;
            }
            
            #shaftCanvas {
                width: 100% !important;
                height: 250px !important;
                max-height: 250px !important;
                border-width: 1px !important;
            }
            
            /* 按钮移动端优化 */
            .btn {
                padding: 12px 20px;
                font-size: 14px;
                margin-bottom: 8px;
                min-height: 44px; /* 确保触摸目标足够大 */
            }
            
            /* 按钮组移动端优化 */
            .button-group {
                flex-direction: column;
                gap: 8px;
            }
            
            .button-group .btn {
                width: 100%;
                margin-bottom: 0;
            }
            
            /* 表格模式移动端优化 */
            .step-item {
                margin-bottom: 15px;
                padding: 12px;
            }
            
            .step-header {
                margin-bottom: 10px;
            }
            
            .step-title {
                font-size: 16px;
            }
            
            .remove-step {
                padding: 4px 8px;
                font-size: 12px;
            }
            
            /* 结果表格移动端优化 */
            .result-table {
                font-size: 12px;
            }
            
            .result-table th,
            .result-table td {
                padding: 6px 4px;
            }
            
            /* 模态框移动端优化 */
            .modal {
                padding: 10px;
            }
            
            .modal-content {
                width: 90%;
                max-width: 300px;
                padding: 15px;
            }
        }
        
        /* 超小屏幕优化 */
        @media (max-width: 480px) {
            .container {
                margin: 2px;
            }
            
            .content {
                padding: 10px 8px;
            }
            
            .header h1 {
                font-size: 16px;
            }
            
            .header p {
                font-size: 12px;
            }
            
            #shaftCanvas {
                height: 200px !important;
                max-height: 200px !important;
            }
            
            .btn {
                padding: 10px 16px;
                font-size: 13px;
            }
        }
        
        /* 移动端触摸优化 */
        @media (max-width: 768px) {
            /* 防止触摸时选中文本 */
            * {
                -webkit-touch-callout: none;
                -webkit-user-select: none;
                -khtml-user-select: none;
                -moz-user-select: none;
                -ms-user-select: none;
                user-select: none;
            }
            
            /* 允许输入框选中文本 */
            input, textarea {
                -webkit-user-select: text;
                -khtml-user-select: text;
                -moz-user-select: text;
                -ms-user-select: text;
                user-select: text;
            }
            
            /* 画布触摸优化 */
            #shaftCanvas {
                touch-action: none;
                -webkit-touch-callout: none;
                -webkit-user-select: none;
            }
            
            /* 按钮触摸优化 */
            .btn {
                touch-action: manipulation;
                -webkit-tap-highlight-color: transparent;
            }
            
            /* 输入框触摸优化 */
            input {
                touch-action: manipulation;
                font-size: 16px; /* 防止iOS缩放 */
            }
            
            /* 移动端提示显示 */
            .mobile-hint {
                display: block !important;
            }
            
            /* 移动端快速操作按钮 */
            .mobile-quick-actions {
                display: block !important;
            }
            
            /* 移动端隐藏大按钮 */
            .mobile-quick-actions + div {
                display: none !important;
            }
        }
        
        /* 桌面端隐藏移动端提示 */
        @media (min-width: 769px) {
            .mobile-hint {
                display: none !important;
            }
            
            .mobile-quick-actions {
                display: none !important;
            }
        }
        
        /* 移动端设备特定样式 */
        .mobile-device .container {
            margin: 0;
            border-radius: 0;
            min-height: 100vh;
        }
        
        .mobile-device .content {
            padding: 10px;
        }
        
        .mobile-device #shaftCanvas {
            border-radius: 4px;
        }
        
        @media (min-width: 769px) {
            .container {
                margin: 20px auto;
            }
            
            .content {
                padding: 40px 30px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>锻造规划计算器</h1>
            <p>圆柱体钢锭锻造成台阶轴规划工具</p>
        </div>
        
        <div class="content">
            <div class="input-group">
                <label>原始钢锭参数 (输入任意两个)</label>
                <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; margin-top: 8px;">
                    <div>
                        <label style="font-size: 14px; color: #666;">直径 (毫米)</label>
                        <input type="number" id="originalDiameter" placeholder="直径" step="0.1" min="0" oninput="calculateThirdParameter()">
                    </div>
                    <div>
                        <label style="font-size: 14px; color: #666;">长度 (毫米)</label>
                        <input type="number" id="originalLength" placeholder="长度" step="0.1" min="0" oninput="calculateThirdParameter()">
                    </div>
                    <div>
                        <label style="font-size: 14px; color: #666;">重量 (千克)</label>
                        <input type="number" id="originalWeight" placeholder="重量" step="0.01" min="0" oninput="calculateThirdParameter()">
                    </div>
                </div>
                <div id="calculatedParameter" style="margin-top: 8px; padding: 8px 12px; background: #e8f4fd; border-radius: 6px; border-left: 3px solid #3498db; display: none;">
                    <span style="font-weight: 500; color: #2c3e50;">计算得出: </span>
                    <span id="calculatedValue" style="color: #3498db; font-weight: 600;"></span>
                </div>
                <div style="margin-top: 8px; padding: 8px 12px; background: #fff3cd; border-radius: 6px; border-left: 3px solid #ffc107; font-size: 12px; color: #856404;">
                    💡 提示：也可以先输入台阶参数，系统会自动计算原始钢锭参数
                </div>
            </div>
            
            <div class="input-group">
                <label>材料密度 (克/立方厘米)</label>
                <select id="materialDensity" onchange="updateDensity()">
                    <option value="7.85">碳钢 (7.85 g/cm³)</option>
                    <option value="7.9">合金钢 (7.9 g/cm³)</option>
                    <option value="8.0">不锈钢 (8.0 g/cm³)</option>
                    <option value="2.7">铝合金 (2.7 g/cm³)</option>
                    <option value="8.9">铜合金 (8.9 g/cm³)</option>
                    <option value="custom">自定义密度</option>
                </select>
                <input type="number" id="customDensity" placeholder="输入自定义密度" step="0.01" min="0" style="margin-top: 8px; display: none;" oninput="updateOriginalWeight()">
            </div>
            
            <div class="input-group">
                <label>台阶轴参数</label>
                <div style="margin-bottom: 16px;">
                    <button class="btn btn-secondary" onclick="toggleInputMode()" style="margin-right: 10px;">切换输入模式</button>
                    <span id="inputModeText" style="color: #666; font-size: 14px;">当前模式: 表格输入</span>
                </div>
                
                                <!-- 可视化图纸模式 -->
                <div id="visualMode" style="display: none;">
                    <div style="background: #f8f9fa; border: 1px solid #e0e0e0; border-radius: 8px; padding: 20px; margin-bottom: 16px;">
                        <div style="text-align: center; margin-bottom: 16px;">
                            <h4 style="margin: 0; color: #2c3e50;">台阶轴可视化设计</h4>
                            <p style="margin: 8px 0 0 0; color: #666; font-size: 14px;">点击画布添加台阶，拖拽调整尺寸</p>
                            <div style="margin-top: 10px;">
                                <button class="btn btn-secondary" onclick="toggleFullscreen()" style="margin-right: 10px;">切换全屏 (F11)</button>
                                <button class="btn btn-secondary" onclick="resetCanvasSize()" style="margin-right: 10px;">重置画布</button>
                                <button class="btn btn-secondary" onclick="toggleDebugMode()" id="debugBtn">调试模式</button>
                            </div>
                            <div style="margin-top: 8px; font-size: 12px; color: #666;">
                                快捷键: F11全屏 | ESC退出 | Ctrl+A添加台阶 | Delete删除选中<br>
                                调试模式: 显示点击区域，帮助定位问题
                            </div>
                        </div>
                        
                        <div style="display: flex; gap: 20px; align-items: flex-start; height: 600px;" class="visual-layout">
                            <!-- 画布区域 -->
                            <div style="flex: 3; display: flex; flex-direction: column;" class="canvas-area">
                                <canvas id="shaftCanvas" width="800" height="500" style="border: 2px solid #3498db; border-radius: 6px; background: white; cursor: crosshair; flex: 1; max-height: 500px;"></canvas>
                                <div style="margin-top: 10px; text-align: center;">
                                    <p style="color: #666; font-size: 12px; margin: 0;">点击台阶选中拖拽调整，点击尺寸标注直接输入数值</p>
                                    <p style="color: #999; font-size: 11px; margin: 4px 0 0 0;" class="mobile-hint">移动端：长按添加台阶，双击删除台阶</p>
                                </div>
                            </div>
                            
                            <!-- 参数显示区域 -->
                            <div style="flex: 1; min-width: 250px; max-width: 300px;" class="params-area">
                                <h5 style="margin: 0 0 12px 0; color: #2c3e50;">台阶参数</h5>
                                <div id="canvasStepsList" style="max-height: 300px; overflow-y: auto;">
                                    <p style="color: #666; font-style: italic; text-align: center; margin: 20px 0;">暂无台阶，请在画布上添加</p>
                                </div>
                                <div style="margin-top: 12px;">
                                    <button class="btn btn-secondary" onclick="addStepToCanvas()" style="width: 100%; margin-bottom: 8px;">添加台阶</button>
                                    <button class="btn btn-secondary" onclick="clearCanvas()" style="width: 100%; background: #e74c3c; margin-bottom: 8px;">清空画布</button>
                                    <button class="btn" onclick="calculateFromCanvas()" style="width: 100%; background: #27ae60; color: white;">开始计算</button>
                                </div>
                                <div class="mobile-quick-actions" style="margin-top: 12px; display: none;">
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px;">
                                        <button class="btn btn-secondary" onclick="addStepToCanvas()" style="font-size: 12px; padding: 8px;">+ 台阶</button>
                                        <button class="btn btn-secondary" onclick="clearCanvas()" style="font-size: 12px; padding: 8px; background: #e74c3c;">清空</button>
                                    </div>
                                </div>
                                <div style="margin-top: 8px; padding: 8px; background: #e8f5e8; border-radius: 4px; border-left: 3px solid #27ae60; font-size: 12px; color: #2c3e50;">
                                    💡 提示：画布模式下可直接计算，系统会自动估算原始钢锭参数
                                </div>
                                <div style="margin-top: 16px; padding: 12px; background: #e8f4fd; border-radius: 6px; border-left: 3px solid #3498db;">
                                    <div style="font-weight: 500; color: #2c3e50; margin-bottom: 8px;">总参数</div>
                                    <div style="font-size: 14px; color: #666;">
                                        <div>台阶数量: <span id="totalStepsCount">0</span></div>
                                        <div>总长度: <span id="totalCanvasLength">0</span> mm</div>
                                        <div>最大直径: <span id="maxCanvasDiameter">0</span> mm</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 表格输入模式 -->
                <div id="tableMode">
                    <div class="steps-container" id="stepsContainer">
                        <!-- 台阶项目将在这里动态添加 -->
                    </div>
                    <div style="display: flex; gap: 10px; margin-top: 16px;" class="button-group">
                        <button class="btn btn-secondary" onclick="addStep()">添加台阶</button>
                        <button class="btn btn-secondary" onclick="generateEngineeringDrawing()" style="background: #27ae60;">生成工程图</button>
                    </div>
                </div>
            </div>
            
            <button class="btn" id="mainCalculateBtn" onclick="calculate()">开始计算</button>
            
            <div class="results" id="results">
                <h3>计算结果</h3>
                <div id="resultContent"></div>
                <button class="btn btn-secondary" onclick="saveToHistory()" style="margin-top: 16px;">保存到历史记录</button>
            </div>
            
            <div class="history-section" style="margin-top: 24px;">
                <h3>历史记录</h3>
                <div id="historyList"></div>
            </div>
        </div>
    </div>

    <script>
        let stepCount = 0;
        let currentResults = null;
        let historyData = [];
        
        // 可视化相关变量
        let canvasSteps = [];
        let selectedStep = null;
        let isDragging = false;
        let dragStartX = 0;
        let dragStartY = 0;
        let currentInputMode = 'table'; // 'table' 或 'visual'
        let debugMode = false; // 调试模式
        
        // 页面加载时添加第一个台阶
        window.onload = function() {
            addStep();
            // 初始化画布事件
            initCanvasEvents();
            // 初始化键盘快捷键
            initKeyboardShortcuts();
            // 监听密度变化，更新所有台阶重量和原始钢锭参数
            document.getElementById('materialDensity').addEventListener('change', function() {
                updateAllStepWeights();
                calculateThirdParameter();
            });
            document.getElementById('customDensity').addEventListener('input', function() {
                updateAllStepWeights();
                calculateThirdParameter();
            });
            // 监听原始钢锭参数变化
            document.getElementById('originalDiameter').addEventListener('input', calculateThirdParameter);
            document.getElementById('originalLength').addEventListener('input', calculateThirdParameter);
            document.getElementById('originalWeight').addEventListener('input', calculateThirdParameter);
            // 加载历史记录
            loadHistory();
            
            // 移动端优化
            initMobileOptimizations();
            
            // 注册Service Worker
            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.register('/sw.js')
                    .then(registration => {
                        console.log('Service Worker注册成功:', registration);
                    })
                    .catch(error => {
                        console.log('Service Worker注册失败:', error);
                    });
            }
        };
        
        function initMobileOptimizations() {
            // 检测是否为移动设备
            const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
            
            if (isMobile) {
                // 移动端特定优化
                document.body.classList.add('mobile-device');
                
                // 调整画布尺寸以适应移动端
                const canvas = document.getElementById('shaftCanvas');
                if (canvas) {
                    const containerWidth = canvas.parentElement.offsetWidth;
                    canvas.style.width = '100%';
                    canvas.style.height = '200px';
                }
                
                // 显示移动端提示
                showMobileToast('移动端已优化，支持触摸操作');
            }
        }
        
        function initKeyboardShortcuts() {
            document.addEventListener('keydown', function(e) {
                // F11 切换全屏
                if (e.key === 'F11') {
                    e.preventDefault();
                    toggleFullscreen();
                }
                // ESC 退出全屏
                if (e.key === 'Escape') {
                    const canvas = document.getElementById('shaftCanvas');
                    if (canvas.style.width === '100vw') {
                        toggleFullscreen();
                    }
                }
                // Ctrl+A 添加台阶
                if (e.ctrlKey && e.key === 'a') {
                    e.preventDefault();
                    if (currentInputMode === 'visual') {
                        addStepToCanvas();
                    } else {
                        addStep();
                    }
                }
                // Delete 删除选中台阶
                if (e.key === 'Delete' && selectedStep) {
                    removeCanvasStep(selectedStep.id);
                    selectedStep = null;
                }
                // Enter 开始计算（在画布模式下）
                if (e.key === 'Enter' && currentInputMode === 'visual') {
                    calculateFromCanvas();
                }
            });
            
            // 移动端手势支持
            initMobileGestures();
        }
        
        function initMobileGestures() {
            const canvas = document.getElementById('shaftCanvas');
            let touchStartTime = 0;
            let touchStartX = 0;
            let touchStartY = 0;
            
            canvas.addEventListener('touchstart', function(e) {
                touchStartTime = Date.now();
                touchStartX = e.touches[0].clientX;
                touchStartY = e.touches[0].clientY;
            });
            
            canvas.addEventListener('touchend', function(e) {
                const touchEndTime = Date.now();
                const touchDuration = touchEndTime - touchStartTime;
                const touchEndX = e.changedTouches[0].clientX;
                const touchEndY = e.changedTouches[0].clientY;
                const deltaX = touchEndX - touchStartX;
                const deltaY = touchEndY - touchStartY;
                const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
                
                // 长按手势（超过500ms）
                if (touchDuration > 500 && distance < 10) {
                    // 长按添加台阶
                    addStepToCanvas();
                    showMobileToast('已添加台阶');
                }
                
                // 双击手势（快速连续点击）
                if (touchDuration < 200 && distance < 10) {
                    // 双击删除选中台阶
                    if (selectedStep) {
                        removeCanvasStep(selectedStep.id);
                        selectedStep = null;
                        showMobileToast('已删除台阶');
                    }
                }
            });
        }
        
        function showMobileToast(message) {
            // 创建移动端提示框
            const toast = document.createElement('div');
            toast.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: rgba(0, 0, 0, 0.8);
                color: white;
                padding: 12px 20px;
                border-radius: 6px;
                font-size: 14px;
                z-index: 10000;
                pointer-events: none;
            `;
            toast.textContent = message;
            document.body.appendChild(toast);
            
            // 2秒后自动移除
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 2000);
        }
        
        function addStep() {
            stepCount++;
            const container = document.getElementById('stepsContainer');
            
            const stepDiv = document.createElement('div');
            stepDiv.className = 'step-item';
            stepDiv.innerHTML = `
                <div class="step-header">
                    <span class="step-title">台阶 ${stepCount}</span>
                    <button class="remove-step" onclick="removeStep(this)">删除</button>
                </div>
                <div class="step-inputs" style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px;">
                    <div>
                        <label style="font-size: 14px; color: #666;">直径 (毫米)</label>
                        <input type="number" class="step-diameter" placeholder="直径" step="0.1" min="0" oninput="updateStepThirdParameter(this)">
                    </div>
                    <div>
                        <label style="font-size: 14px; color: #666;">长度 (毫米)</label>
                        <input type="number" class="step-length" placeholder="长度" step="0.1" min="0" oninput="updateStepThirdParameter(this)">
                    </div>
                    <div>
                        <label style="font-size: 14px; color: #666;">重量 (千克)</label>
                        <input type="number" class="step-weight-input" placeholder="重量" step="0.01" min="0" oninput="updateStepThirdParameter(this)">
                    </div>
                </div>
                <div class="step-calculated" style="margin-top: 8px; padding: 8px 12px; background: #e8f4fd; border-radius: 6px; border-left: 3px solid #3498db; display: none;">
                    <span style="font-weight: 500; color: #2c3e50;">计算得出: </span>
                    <span class="calculated-step-value" style="color: #3498db; font-weight: 600;"></span>
                </div>
            `;
            
            container.appendChild(stepDiv);
        }
        
        function removeStep(button) {
            button.parentElement.parentElement.remove();
            updateStepNumbers();
        }
        
        function updateStepNumbers() {
            const steps = document.querySelectorAll('.step-item');
            steps.forEach((step, index) => {
                step.querySelector('.step-title').textContent = `台阶 ${index + 1}`;
            });
            stepCount = steps.length;
        }
        
        // 可视化相关函数
        function toggleInputMode() {
            currentInputMode = currentInputMode === 'table' ? 'visual' : 'table';
            const tableMode = document.getElementById('tableMode');
            const visualMode = document.getElementById('visualMode');
            const modeText = document.getElementById('inputModeText');
            const mainCalculateBtn = document.getElementById('mainCalculateBtn');
            
            if (currentInputMode === 'visual') {
                tableMode.style.display = 'none';
                visualMode.style.display = 'block';
                modeText.textContent = '当前模式: 可视化图纸';
                
                // 隐藏主计算按钮（可视化模式有自己的计算按钮）
                mainCalculateBtn.style.display = 'none';
                
                // 从表格数据生成画布数据
                if (canvasSteps.length === 0) {
                    const stepItems = document.querySelectorAll('.step-item');
                    let hasValidData = false;
                    
                    stepItems.forEach((stepItem, index) => {
                        const diameter = parseFloat(stepItem.querySelector('.step-diameter').value) || 0;
                        const length = parseFloat(stepItem.querySelector('.step-length').value) || 0;
                        
                        if (diameter > 0 && length > 0) {
                            canvasSteps.push({
                                id: Date.now() + index,
                                diameter: diameter,
                                length: length,
                                color: getRandomColor()
                            });
                            hasValidData = true;
                        }
                    });
                    
                    // 如果没有有效数据，添加默认台阶
                    if (!hasValidData) {
                        addDefaultSteps();
                    }
                }
                
                initCanvas();
            } else {
                tableMode.style.display = 'block';
                visualMode.style.display = 'none';
                modeText.textContent = '当前模式: 表格输入';
                
                // 显示主计算按钮（表格模式使用主计算按钮）
                mainCalculateBtn.style.display = 'block';
            }
        }
        
        function initCanvas() {
            drawAllSteps();
        }
        
        function addStepToCanvas() {
            const step = {
                id: Date.now(),
                diameter: 200,
                length: 150,
                color: getRandomColor()
            };
            
            canvasSteps.push(step);
            updateCanvasStepsList();
            drawAllSteps();
        }
        
        // 添加一些默认台阶用于演示
        function addDefaultSteps() {
            if (canvasSteps.length === 0) {
                const defaultSteps = [
                    { diameter: 300, length: 200, color: '#3498db' },
                    { diameter: 250, length: 150, color: '#e74c3c' },
                    { diameter: 200, length: 100, color: '#2ecc71' }
                ];
                
                defaultSteps.forEach((stepData, index) => {
                    canvasSteps.push({
                        id: Date.now() + index,
                        diameter: stepData.diameter,
                        length: stepData.length,
                        color: stepData.color
                    });
                });
                
                updateCanvasStepsList();
                drawAllSteps();
            }
        }
        
        function clearCanvas() {
            canvasSteps = [];
            updateCanvasStepsList();
            initCanvas();
        }
        
        function drawAllSteps() {
            const canvas = document.getElementById('shaftCanvas');
            const ctx = canvas.getContext('2d');
            
            // 清空画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 设置背景
            ctx.fillStyle = '#f8f9fa';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 绘制图纸边框
            ctx.strokeStyle = '#2c3e50';
            ctx.lineWidth = 2;
            ctx.strokeRect(10, 10, canvas.width - 20, canvas.height - 20);
            
            // 绘制标题
            ctx.fillStyle = '#2c3e50';
            ctx.font = 'bold 16px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('台阶轴工程图', canvas.width / 2, 35);
            
            // 绘制中心轴线
            const centerY = canvas.height / 2;
            ctx.strokeStyle = '#2c3e50';
            ctx.lineWidth = 1;
            ctx.setLineDash([8, 4]);
            ctx.beginPath();
            ctx.moveTo(60, centerY);
            ctx.lineTo(canvas.width - 60, centerY);
            ctx.stroke();
            ctx.setLineDash([]);
            
            // 绘制所有台阶
            canvasSteps.forEach((step, index) => {
                drawStep(ctx, step, index);
            });
        }
        
        function drawStep(ctx, step, index) {
            const centerY = ctx.canvas.height / 2;
            
            // 防止空数组导致的错误
            if (canvasSteps.length === 0) return;
            
            const maxDiameter = Math.max(...canvasSteps.map(s => s.diameter));
            const totalLength = canvasSteps.reduce((sum, s) => sum + s.length, 0);
            
            // 计算缩放比例，确保图形适合画布
            const availableWidth = ctx.canvas.width - 200;
            const availableHeight = ctx.canvas.height - 150;
            const scaleX = availableWidth / totalLength;
            const scaleY = availableHeight / maxDiameter;
            const scale = Math.min(scaleX, scaleY, 1.2); // 增加最大缩放限制
            
            // 计算当前台阶的位置（连接在一起，无间距）
            let startX = 120;
            for (let i = 0; i < index; i++) {
                startX += canvasSteps[i].length * scale;
            }
            
            const width = step.length * scale;
            const height = step.diameter * scale;
            const x = startX;
            const y = centerY - height / 2;
            
            // 绘制台阶轮廓（工程图风格）
            ctx.strokeStyle = selectedStep === step ? '#e74c3c' : '#000000';
            ctx.lineWidth = selectedStep === step ? 3 : 1.5;
            
            // 绘制外轮廓
            ctx.beginPath();
            ctx.moveTo(x, y);
            ctx.lineTo(x + width, y);
            ctx.lineTo(x + width, y + height);
            ctx.lineTo(x, y + height);
            ctx.closePath();
            ctx.stroke();
            
            // 绘制中心线
            ctx.strokeStyle = '#2c3e50';
            ctx.lineWidth = 0.5;
            ctx.setLineDash([3, 2]);
            ctx.beginPath();
            ctx.moveTo(x, centerY);
            ctx.lineTo(x + width, centerY);
            ctx.stroke();
            ctx.setLineDash([]);
            
            // 绘制尺寸线
            drawDimensionLines(ctx, x, y, width, height, step, index);
            
            // 绘制台阶编号
            ctx.fillStyle = '#2c3e50';
            ctx.font = 'bold 12px Arial';
            ctx.textAlign = 'center';
            ctx.fillText(`${index + 1}`, x + width / 2, y + height / 2 + 4);
            
            // 重置文本对齐
            ctx.textAlign = 'left';
        }
        
        function drawDimensionLines(ctx, x, y, width, height, step, index) {
            const centerY = ctx.canvas.height / 2;
            
            // 绘制直径尺寸线
            ctx.strokeStyle = '#2c3e50';
            ctx.lineWidth = 0.5;
            
            // 直径尺寸线
            const dimY = y - 15;
            ctx.beginPath();
            ctx.moveTo(x + width / 2, y);
            ctx.lineTo(x + width / 2, dimY);
            ctx.moveTo(x + width / 2 - 5, dimY);
            ctx.lineTo(x + width / 2 + 5, dimY);
            ctx.stroke();
            
            // 直径标注（可点击）
            ctx.fillStyle = '#3498db';
            ctx.font = 'bold 12px Arial';
            ctx.textAlign = 'center';
            const diameterText = `φ${step.diameter}`;
            const diameterWidth = ctx.measureText(diameterText).width;
            ctx.fillText(diameterText, x + width / 2, dimY - 5);
            
            // 保存直径标注的点击区域
            step.diameterClickArea = {
                x: x + width / 2 - diameterWidth / 2 - 5,
                y: dimY - 20,
                width: diameterWidth + 10,
                height: 15
            };
            
            // 调试：绘制点击区域边框（红色半透明）
            if (debugMode) {
                ctx.strokeStyle = 'rgba(255, 0, 0, 0.5)';
                ctx.lineWidth = 2;
                ctx.strokeRect(step.diameterClickArea.x, step.diameterClickArea.y, step.diameterClickArea.width, step.diameterClickArea.height);
                
                // 添加调试文本
                ctx.fillStyle = 'rgba(255, 0, 0, 0.8)';
                ctx.font = '10px Arial';
                ctx.fillText(`D:${step.diameterClickArea.x.toFixed(0)},${step.diameterClickArea.y.toFixed(0)}`, 
                    step.diameterClickArea.x, step.diameterClickArea.y - 5);
            }
            
            // 长度尺寸线
            const lengthY = y + height + 15;
            ctx.beginPath();
            ctx.moveTo(x, y + height);
            ctx.lineTo(x, lengthY);
            ctx.moveTo(x + width, y + height);
            ctx.lineTo(x + width, lengthY);
            ctx.moveTo(x, lengthY);
            ctx.lineTo(x + width, lengthY);
            ctx.stroke();
            
            // 长度标注（可点击）
            ctx.fillStyle = '#3498db';
            const lengthText = `${step.length}`;
            const lengthWidth = ctx.measureText(lengthText).width;
            ctx.fillText(lengthText, x + width / 2, lengthY + 12);
            
            // 保存长度标注的点击区域
            step.lengthClickArea = {
                x: x + width / 2 - lengthWidth / 2 - 5,
                y: lengthY - 5,
                width: lengthWidth + 10,
                height: 15
            };
            
            // 调试：绘制点击区域边框（绿色半透明）
            if (debugMode) {
                ctx.strokeStyle = 'rgba(0, 255, 0, 0.5)';
                ctx.lineWidth = 2;
                ctx.strokeRect(step.lengthClickArea.x, step.lengthClickArea.y, step.lengthClickArea.width, step.lengthClickArea.height);
                
                // 添加调试文本
                ctx.fillStyle = 'rgba(0, 255, 0, 0.8)';
                ctx.font = '10px Arial';
                ctx.fillText(`L:${step.lengthClickArea.x.toFixed(0)},${step.lengthClickArea.y.toFixed(0)}`, 
                    step.lengthClickArea.x, step.lengthClickArea.y - 5);
            }
            
            // 绘制箭头
            drawArrow(ctx, x, lengthY, x + 5, lengthY);
            drawArrow(ctx, x + width, lengthY, x + width - 5, lengthY);
        }
        
        function drawArrow(ctx, fromX, fromY, toX, toY) {
            const headLength = 5;
            const angle = Math.atan2(toY - fromY, toX - fromX);
            
            ctx.beginPath();
            ctx.moveTo(fromX, fromY);
            ctx.lineTo(toX, toY);
            ctx.lineTo(toX - headLength * Math.cos(angle - Math.PI / 6), toY - headLength * Math.sin(angle - Math.PI / 6));
            ctx.moveTo(toX, toY);
            ctx.lineTo(toX - headLength * Math.cos(angle + Math.PI / 6), toY - headLength * Math.sin(angle + Math.PI / 6));
            ctx.stroke();
        }
        
        function getRandomColor() {
            const colors = ['#3498db', '#e74c3c', '#2ecc71', '#f39c12', '#9b59b6', '#1abc9c'];
            return colors[Math.floor(Math.random() * colors.length)];
        }
        
        function updateCanvasStepsList() {
            const container = document.getElementById('canvasStepsList');
            const totalStepsCount = document.getElementById('totalStepsCount');
            const totalCanvasLength = document.getElementById('totalCanvasLength');
            const maxCanvasDiameter = document.getElementById('maxCanvasDiameter');
            
            if (canvasSteps.length === 0) {
                container.innerHTML = '<p style="color: #666; font-style: italic; text-align: center; margin: 20px 0;">暂无台阶，请在画布上添加</p>';
                totalStepsCount.textContent = '0';
                totalCanvasLength.textContent = '0';
                maxCanvasDiameter.textContent = '0';
                return;
            }
            
            let html = '';
            let totalLength = 0;
            let maxDiameter = 0;
            
            canvasSteps.forEach((step, index) => {
                totalLength += step.length;
                maxDiameter = Math.max(maxDiameter, step.diameter);
                
                html += `
                    <div style="background: white; border: 1px solid #e0e0e0; border-radius: 6px; padding: 12px; margin-bottom: 8px;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                            <span style="font-weight: 500; color: #2c3e50;">台阶 ${index + 1}</span>
                            <button onclick="removeCanvasStep(${step.id})" style="background: #e74c3c; color: white; border: none; border-radius: 4px; padding: 4px 8px; font-size: 12px; cursor: pointer;">删除</button>
                        </div>
                        <div style="font-size: 14px; color: #666;">
                            <div style="display: flex; justify-content: space-between;">
                                <span>直径:</span>
                                <span style="font-weight: 500;">${step.diameter} mm</span>
                            </div>
                            <div style="display: flex; justify-content: space-between;">
                                <span>长度:</span>
                                <span style="font-weight: 500;">${step.length} mm</span>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
            totalStepsCount.textContent = canvasSteps.length;
            totalCanvasLength.textContent = totalLength;
            maxCanvasDiameter.textContent = maxDiameter;
        }
        
        function removeCanvasStep(stepId) {
            canvasSteps = canvasSteps.filter(step => step.id !== stepId);
            updateCanvasStepsList();
            drawAllSteps();
        }
        
        // 画布事件处理
        function initCanvasEvents() {
            const canvas = document.getElementById('shaftCanvas');
            
            // 移除旧的事件监听器（如果存在）
            if (canvas._mousedownHandler) {
                canvas.removeEventListener('mousedown', canvas._mousedownHandler);
                canvas.removeEventListener('touchstart', canvas._mousedownHandler);
            }
            if (canvas._mousemoveHandler) {
                canvas.removeEventListener('mousemove', canvas._mousemoveHandler);
                canvas.removeEventListener('touchmove', canvas._mousemoveHandler);
            }
            if (canvas._mouseupHandler) {
                canvas.removeEventListener('mouseup', canvas._mouseupHandler);
                canvas.removeEventListener('touchend', canvas._mouseupHandler);
            }
            
            // 创建新的事件处理函数
            canvas._mousedownHandler = function(e) {
                // 阻止默认行为（防止移动端滚动）
                e.preventDefault();
                
                const coords = getCanvasCoordinates(e);
                const x = coords.x;
                const y = coords.y;
                
                if (debugMode) {
                    console.log('点击坐标:', x, y);
                    console.log('画布尺寸:', canvas.width, 'x', canvas.height);
                    console.log('画布样式尺寸:', canvas.style.width, 'x', canvas.style.height);
                }
                
                // 检查是否点击了尺寸标注
                const clickedDimension = getDimensionAtPosition(x, y);
                if (clickedDimension) {
                    if (debugMode) {
                        console.log('检测到尺寸标注点击:', clickedDimension.type);
                    }
                    console.log('准备调用handleDimensionClick');
                    handleDimensionClick(clickedDimension);
                    console.log('handleDimensionClick调用完成');
                    return;
                }
                
                // 检查是否点击了台阶
                const clickedStep = getStepAtPosition(x, y);
                if (clickedStep) {
                    selectedStep = clickedStep;
                    isDragging = true;
                    dragStartX = x;
                    dragStartY = y;
                    drawAllSteps();
                }
            };
            
            canvas._mousemoveHandler = function(e) {
                // 阻止默认行为（防止移动端滚动）
                e.preventDefault();
                
                const coords = getCanvasCoordinates(e);
                const x = coords.x;
                const y = coords.y;
                
                // 检查鼠标悬停
                const hoveredDimension = getDimensionAtPosition(x, y);
                if (hoveredDimension) {
                    canvas.style.cursor = 'pointer';
                } else {
                    canvas.style.cursor = 'crosshair';
                }
                
                if (isDragging && selectedStep) {
                    const deltaX = x - dragStartX;
                    const deltaY = y - dragStartY;
                    
                    // 计算当前缩放比例（使用实际画布尺寸）
                    const maxDiameter = Math.max(...canvasSteps.map(s => s.diameter));
                    const totalLength = canvasSteps.reduce((sum, s) => sum + s.length, 0);
                    const availableWidth = canvas.width - 200;
                    const availableHeight = canvas.height - 150;
                    const scaleX = availableWidth / totalLength;
                    const scaleY = availableHeight / maxDiameter;
                    const scale = Math.min(scaleX, scaleY, 1.2);
                    
                    // 调整台阶尺寸
                    selectedStep.length = Math.max(20, selectedStep.length + deltaX / scale);
                    selectedStep.diameter = Math.max(20, selectedStep.diameter - deltaY / scale);
                    
                    dragStartX = x;
                    dragStartY = y;
                    
                    updateCanvasStepsList();
                    drawAllSteps();
                }
            };
            
            canvas._mouseupHandler = function() {
                isDragging = false;
                selectedStep = null;
            };
            
            // 添加事件监听器
            canvas.addEventListener('mousedown', canvas._mousedownHandler);
            canvas.addEventListener('mousemove', canvas._mousemoveHandler);
            canvas.addEventListener('mouseup', canvas._mouseupHandler);
            
            // 添加触摸事件支持（移动端）
            canvas.addEventListener('touchstart', canvas._mousedownHandler, { passive: false });
            canvas.addEventListener('touchmove', canvas._mousemoveHandler, { passive: false });
            canvas.addEventListener('touchend', canvas._mouseupHandler, { passive: false });
        }
        
        function testCanvasEvents() {
            const canvas = document.getElementById('shaftCanvas');
            console.log('=== 画布事件测试 ===');
            console.log('画布元素:', canvas);
            console.log('画布尺寸:', canvas.width, 'x', canvas.height);
            console.log('画布样式尺寸:', canvas.style.width, 'x', canvas.style.height);
            console.log('事件处理器:', {
                mousedown: canvas._mousedownHandler,
                mousemove: canvas._mousemoveHandler,
                mouseup: canvas._mouseupHandler
            });
            console.log('台阶数据:', canvasSteps);
            console.log('调试模式:', debugMode);
            
            // 重新初始化事件
            initCanvasEvents();
            console.log('事件重新初始化完成');
            
            alert('事件测试完成，请查看控制台输出');
        }
        
        function testModal() {
            console.log('=== 模态框测试 ===');
            
            // 创建测试模态框
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.5);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 20000;
            `;
            
            const inputBox = document.createElement('div');
            inputBox.style.cssText = `
                background: white;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.3);
                min-width: 300px;
            `;
            
            inputBox.innerHTML = `
                <h3 style="margin: 0 0 15px 0; color: #2c3e50;">测试模态框</h3>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; color: #666;">测试输入:</label>
                    <input type="number" id="testInput" value="100" step="0.1" min="1" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;">
                </div>
                <div style="text-align: right;">
                    <button id="testCancelBtn" style="background: #95a5a6; color: white; border: none; padding: 8px 16px; border-radius: 4px; margin-right: 10px; cursor: pointer;">取消</button>
                    <button id="testConfirmBtn" style="background: #3498db; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">确定</button>
                </div>
            `;
            
            modal.appendChild(inputBox);
            
            // 在全屏模式下，确保模态框添加到正确的父元素
            if (isFullscreen) {
                // 全屏模式下，添加到visualMode容器
                const visualMode = document.getElementById('visualMode');
                visualMode.appendChild(modal);
                console.log('全屏模式：测试模态框添加到visualMode');
            } else {
                // 普通模式下，添加到body
                document.body.appendChild(modal);
                console.log('普通模式：测试模态框添加到body');
            }
            
            console.log('测试模态框已创建:', modal);
            console.log('模态框z-index:', modal.style.zIndex);
            console.log('当前全屏状态:', document.getElementById('shaftCanvas').style.width === '100vw');
            
            // 事件处理
            inputBox.querySelector('#testCancelBtn').onclick = function() {
                document.body.removeChild(modal);
                console.log('测试模态框已关闭');
            };
            
            inputBox.querySelector('#testConfirmBtn').onclick = function() {
                const value = inputBox.querySelector('#testInput').value;
                console.log('测试输入值:', value);
                document.body.removeChild(modal);
            };
            
            const input = inputBox.querySelector('#testInput');
            input.focus();
            input.select();
        }
        
        // 获取画布坐标的辅助函数
        function getCanvasCoordinates(e) {
            const canvas = document.getElementById('shaftCanvas');
            const rect = canvas.getBoundingClientRect();
            
            // 计算缩放比例
            const scaleX = canvas.width / rect.width;
            const scaleY = canvas.height / rect.height;
            
            // 获取坐标（支持触摸事件）
            let clientX, clientY;
            if (e.touches && e.touches.length > 0) {
                // 触摸事件
                clientX = e.touches[0].clientX;
                clientY = e.touches[0].clientY;
            } else {
                // 鼠标事件
                clientX = e.clientX;
                clientY = e.clientY;
            }
            
            // 转换坐标
            const x = (clientX - rect.left) * scaleX;
            const y = (clientY - rect.top) * scaleY;
            
            if (debugMode) {
                console.log('原始坐标:', clientX, clientY);
                console.log('画布边界:', rect);
                console.log('缩放比例:', scaleX, scaleY);
                console.log('转换后坐标:', x, y);
            }
            
            return { x, y };
        }
        
        function getDimensionAtPosition(x, y) {
            // 遍历所有台阶，检查点击区域
            for (let i = canvasSteps.length - 1; i >= 0; i--) {
                const step = canvasSteps[i];
                
                // 检查直径标注点击区域
                if (step.diameterClickArea && 
                    x >= step.diameterClickArea.x && 
                    x <= step.diameterClickArea.x + step.diameterClickArea.width &&
                    y >= step.diameterClickArea.y && 
                    y <= step.diameterClickArea.y + step.diameterClickArea.height) {
                    if (debugMode) {
                        console.log('点击了直径标注:', step.diameter);
                        console.log('点击区域:', step.diameterClickArea);
                    }
                    return { step: step, type: 'diameter' };
                }
                
                // 检查长度标注点击区域
                if (step.lengthClickArea && 
                    x >= step.lengthClickArea.x && 
                    x <= step.lengthClickArea.x + step.lengthClickArea.width &&
                    y >= step.lengthClickArea.y && 
                    y <= step.lengthClickArea.y + step.lengthClickArea.height) {
                    if (debugMode) {
                        console.log('点击了长度标注:', step.length);
                        console.log('点击区域:', step.lengthClickArea);
                    }
                    return { step: step, type: 'length' };
                }
            }
            
            if (debugMode) {
                console.log('未检测到尺寸标注点击');
            }
            return null;
        }
        
        function handleDimensionClick(dimension) {
            const step = dimension.step;
            const type = dimension.type;
            const currentValue = type === 'diameter' ? step.diameter : step.length;
            const unit = type === 'diameter' ? 'mm' : 'mm';
            const label = type === 'diameter' ? '直径' : '长度';
            
            console.log('handleDimensionClick 被调用:', { step, type, currentValue, label });
            
            // 检查是否在全屏模式下
            const isFullscreen = document.getElementById('shaftCanvas').style.width === '100vw';
            if (isFullscreen) {
                // 全屏模式下使用原生prompt，更可靠
                const newValue = prompt(`请输入新的${label}值 (${unit}):`, currentValue);
                if (newValue !== null && !isNaN(newValue) && newValue > 0) {
                    const numValue = parseFloat(newValue);
                    if (type === 'diameter') {
                        step.diameter = numValue;
                    } else {
                        step.length = numValue;
                    }
                    updateCanvasStepsList();
                    drawAllSteps();
                    console.log(`${label}已更新为:`, numValue);
                }
                return;
            }
            
            // 创建模态输入框
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.5);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 20000;
            `;
            
            const inputBox = document.createElement('div');
            inputBox.style.cssText = `
                background: white;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.3);
                min-width: 300px;
            `;
            
            inputBox.innerHTML = `
                <h3 style="margin: 0 0 15px 0; color: #2c3e50;">修改${label}</h3>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; color: #666;">${label} (${unit}):</label>
                    <input type="number" id="dimensionInput" value="${currentValue}" step="0.1" min="1" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;">
                </div>
                <div style="text-align: right;">
                    <button id="cancelBtn" style="background: #95a5a6; color: white; border: none; padding: 8px 16px; border-radius: 4px; margin-right: 10px; cursor: pointer;">取消</button>
                    <button id="confirmBtn" style="background: #3498db; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">确定</button>
                </div>
            `;
            
            modal.appendChild(inputBox);
            
            // 在全屏模式下，确保模态框添加到正确的父元素
            if (isFullscreen) {
                // 全屏模式下，添加到visualMode容器
                const visualMode = document.getElementById('visualMode');
                visualMode.appendChild(modal);
                console.log('全屏模式：模态框添加到visualMode');
            } else {
                // 普通模式下，添加到body
                document.body.appendChild(modal);
                console.log('普通模式：模态框添加到body');
            }
            
            console.log('模态框已添加到DOM:', modal);
            console.log('模态框样式:', modal.style.cssText);
            
            const input = inputBox.querySelector('#dimensionInput');
            input.focus();
            input.select();
            
            // 事件处理
            inputBox.querySelector('#cancelBtn').onclick = function() {
                document.body.removeChild(modal);
            };
            
            inputBox.querySelector('#confirmBtn').onclick = function() {
                const newValue = parseFloat(input.value);
                if (!isNaN(newValue) && newValue > 0) {
                    if (type === 'diameter') {
                        step.diameter = newValue;
                    } else {
                        step.length = newValue;
                    }
                    
                    updateCanvasStepsList();
                    drawAllSteps();
                }
                document.body.removeChild(modal);
            };
            
            // 回车确认，ESC取消
            input.onkeydown = function(e) {
                if (e.key === 'Enter') {
                    inputBox.querySelector('#confirmBtn').click();
                } else if (e.key === 'Escape') {
                    inputBox.querySelector('#cancelBtn').click();
                }
            };
            
            // 点击背景取消
            modal.onclick = function(e) {
                if (e.target === modal) {
                    inputBox.querySelector('#cancelBtn').click();
                }
            };
        }
        
        function generateEngineeringDrawing() {
            // 从表格数据生成画布数据
            canvasSteps = [];
            const stepItems = document.querySelectorAll('.step-item');
            
            stepItems.forEach((stepItem, index) => {
                const diameter = parseFloat(stepItem.querySelector('.step-diameter').value) || 0;
                const length = parseFloat(stepItem.querySelector('.step-length').value) || 0;
                
                if (diameter > 0 && length > 0) {
                    canvasSteps.push({
                        id: Date.now() + index,
                        diameter: diameter,
                        length: length,
                        color: getRandomColor()
                    });
                }
            });
            
            if (canvasSteps.length === 0) {
                alert('请先添加台阶数据！');
                return;
            }
            
            // 切换到可视化模式并显示工程图
            currentInputMode = 'visual';
            const tableMode = document.getElementById('tableMode');
            const visualMode = document.getElementById('visualMode');
            const modeText = document.getElementById('inputModeText');
            
            tableMode.style.display = 'none';
            visualMode.style.display = 'block';
            modeText.textContent = '当前模式: 可视化图纸';
            
            updateCanvasStepsList();
            initCanvas();
        }
        
        function toggleFullscreen() {
            const canvas = document.getElementById('shaftCanvas');
            const visualMode = document.getElementById('visualMode');
            
            if (canvas.style.width === '100vw') {
                // 退出全屏
                canvas.style.width = '800px';
                canvas.style.height = '500px';
                canvas.width = 800;
                canvas.height = 500;
                visualMode.style.position = 'static';
                visualMode.style.zIndex = 'auto';
                visualMode.style.width = 'auto';
                visualMode.style.height = 'auto';
                visualMode.style.background = 'transparent';
                
                // 移除全屏控制按钮
                const fullscreenControls = document.getElementById('fullscreenControls');
                if (fullscreenControls) {
                    fullscreenControls.remove();
                }
            } else {
                // 进入全屏
                canvas.style.width = '100vw';
                canvas.style.height = '90vh';
                canvas.width = window.innerWidth;
                canvas.height = window.innerHeight * 0.9;
                visualMode.style.position = 'fixed';
                visualMode.style.top = '0';
                visualMode.style.left = '0';
                visualMode.style.width = '100vw';
                visualMode.style.height = '100vh';
                visualMode.style.zIndex = '9999';
                visualMode.style.background = 'white';
                visualMode.style.overflow = 'auto';
                
                // 添加全屏控制按钮
                addFullscreenControls();
                
                // 强制重新绑定画布事件
                setTimeout(() => {
                    initCanvasEvents();
                    console.log('全屏模式事件重新绑定完成');
                }, 200);
            }
            
            // 重新绘制
            drawAllSteps();
            
            // 重新初始化画布事件（确保全屏模式下事件正常工作）
            setTimeout(() => {
                initCanvasEvents();
            }, 100);
        }
        
        function addFullscreenControls() {
            // 移除已存在的控制按钮
            const existingControls = document.getElementById('fullscreenControls');
            if (existingControls) {
                existingControls.remove();
            }
            
            // 创建全屏控制面板
            const controls = document.createElement('div');
            controls.id = 'fullscreenControls';
            controls.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 10000;
                background: rgba(255, 255, 255, 0.95);
                padding: 15px;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.2);
                display: flex;
                flex-direction: column;
                gap: 10px;
            `;
            
            controls.innerHTML = `
                <div style="font-weight: bold; color: #2c3e50; margin-bottom: 5px;">全屏模式</div>
                <button onclick="toggleFullscreen()" style="background: #e74c3c; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">退出全屏</button>
                <button onclick="calculateFromCanvas()" style="background: #27ae60; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">开始计算</button>
                <button onclick="toggleDebugMode()" id="fullscreenDebugBtn" style="background: #95a5a6; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">调试模式</button>
                <div style="font-size: 12px; color: #666; margin-top: 5px;">
                    点击尺寸标注输入数值<br>
                    拖拽台阶调整尺寸<br>
                    快捷键: Enter计算 | ESC退出<br>
                    💡 自动估算原始钢锭参数<br>
                    📝 全屏模式使用原生输入框
                </div>
                <button onclick="testCanvasEvents()" style="background: #f39c12; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 11px; margin-bottom: 5px;">测试事件</button>
                <button onclick="testModal()" style="background: #9b59b6; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 11px;">测试模态框</button>
            `;
            
            document.body.appendChild(controls);
            
            // 同步调试模式状态
            const debugBtn = document.getElementById('debugBtn');
            const fullscreenDebugBtn = document.getElementById('fullscreenDebugBtn');
            if (debugMode) {
                fullscreenDebugBtn.style.background = '#e74c3c';
                fullscreenDebugBtn.textContent = '关闭调试';
            }
        }
        
        function resetCanvasSize() {
            const canvas = document.getElementById('shaftCanvas');
            const visualMode = document.getElementById('visualMode');
            
            canvas.style.width = '800px';
            canvas.style.height = '500px';
            canvas.width = 800;
            canvas.height = 500;
            visualMode.style.position = 'static';
            visualMode.style.zIndex = 'auto';
            visualMode.style.width = 'auto';
            visualMode.style.height = 'auto';
            visualMode.style.background = 'transparent';
            
            drawAllSteps();
        }
        
        function toggleDebugMode() {
            debugMode = !debugMode;
            const debugBtn = document.getElementById('debugBtn');
            const fullscreenDebugBtn = document.getElementById('fullscreenDebugBtn');
            
            if (debugMode) {
                debugBtn.style.background = '#e74c3c';
                debugBtn.textContent = '关闭调试';
                if (fullscreenDebugBtn) {
                    fullscreenDebugBtn.style.background = '#e74c3c';
                    fullscreenDebugBtn.textContent = '关闭调试';
                }
            } else {
                debugBtn.style.background = '#95a5a6';
                debugBtn.textContent = '调试模式';
                if (fullscreenDebugBtn) {
                    fullscreenDebugBtn.style.background = '#95a5a6';
                    fullscreenDebugBtn.textContent = '调试模式';
                }
            }
            drawAllSteps();
        }
        
        function calculateFromCanvas() {
            // 检查是否有台阶数据
            if (canvasSteps.length === 0) {
                alert('请先在画布上添加台阶！');
                return;
            }
            
            // 检查原始钢锭参数
            const originalDiameter = parseFloat(document.getElementById('originalDiameter').value) || 0;
            const originalLength = parseFloat(document.getElementById('originalLength').value) || 0;
            const originalWeight = parseFloat(document.getElementById('originalWeight').value) || 0;
            const density = parseFloat(document.getElementById('materialDensity').value);
            
            // 如果原始钢锭参数不足，尝试自动计算
            let finalOriginalDiameter = originalDiameter;
            let finalOriginalLength = originalLength;
            let finalOriginalWeight = originalWeight;
            
            // 计算台阶轴的总重量和体积
            let totalStepWeight = 0;
            let totalStepVolume = 0;
            
            canvasSteps.forEach(step => {
                const volume = calculateVolume(step.diameter, step.length);
                const weight = calculateWeight(volume, density);
                totalStepVolume += volume;
                totalStepWeight += weight;
            });
            
            // 如果原始钢锭参数不足，使用台阶轴数据估算
            if (originalDiameter === 0 && originalLength === 0 && originalWeight === 0) {
                // 基于体积守恒原理计算最小所需原始钢锭参数
                
                // 1. 计算台阶轴总体积
                let totalStepVolume = 0;
                canvasSteps.forEach(step => {
                    const volume = calculateVolume(step.diameter, step.length);
                    totalStepVolume += volume;
                });
                
                // 2. 考虑锻造损耗（通常5-15%，这里取10%）
                const forgingLoss = 0.10; // 10%损耗
                const requiredVolume = totalStepVolume / (1 - forgingLoss);
                
                // 3. 计算最小所需原始钢锭长度（基于体积守恒）
                const maxStepDiameter = Math.max(...canvasSteps.map(s => s.diameter));
                const minRequiredLength = requiredVolume / (Math.PI * Math.pow(maxStepDiameter / 2, 2));
                
                // 4. 估算原始钢锭参数（考虑实际锻造工艺）
                const estimatedDiameter = maxStepDiameter * 1.15; // 考虑锻造余量
                const estimatedLength = minRequiredLength * 1.2; // 考虑端部损耗
                const estimatedWeight = totalStepWeight / (1 - forgingLoss); // 考虑锻造损耗
                
                // 自动填充估算值
                document.getElementById('originalDiameter').value = estimatedDiameter.toFixed(1);
                document.getElementById('originalLength').value = estimatedLength.toFixed(1);
                document.getElementById('originalWeight').value = estimatedWeight.toFixed(2);
                
                finalOriginalDiameter = estimatedDiameter;
                finalOriginalLength = estimatedLength;
                finalOriginalWeight = estimatedWeight;
                
                console.log('基于体积守恒的原始钢锭参数估算:', {
                    totalStepVolume: totalStepVolume.toFixed(2),
                    requiredVolume: requiredVolume.toFixed(2),
                    minRequiredLength: minRequiredLength.toFixed(1),
                    estimatedDiameter: estimatedDiameter.toFixed(1),
                    estimatedLength: estimatedLength.toFixed(1),
                    estimatedWeight: estimatedWeight.toFixed(2),
                    forgingLoss: (forgingLoss * 100) + '%'
                });
            }
            
            // 将画布数据同步到表格模式
            syncCanvasToTable();
            
            // 执行计算
            calculate();
        }
        
        function syncCanvasToTable() {
            // 获取密度
            const density = parseFloat(document.getElementById('materialDensity').value);
            
            // 清空现有台阶
            const stepsContainer = document.getElementById('stepsContainer');
            stepsContainer.innerHTML = '';
            stepCount = 0;
            
            // 从画布数据添加台阶到表格
            canvasSteps.forEach((step, index) => {
                addStep();
                const stepItems = document.querySelectorAll('.step-item');
                const currentStepItem = stepItems[stepItems.length - 1];
                
                const diameterInput = currentStepItem.querySelector('.step-diameter');
                const lengthInput = currentStepItem.querySelector('.step-length');
                const weightInput = currentStepItem.querySelector('.step-weight-input');
                
                diameterInput.value = step.diameter;
                lengthInput.value = step.length;
                
                // 计算重量
                const volume = calculateVolume(step.diameter, step.length);
                const weight = calculateWeight(volume, density);
                weightInput.value = weight.toFixed(2);
                
                // 更新显示
                const calculatedDiv = currentStepItem.querySelector('.step-calculated');
                const calculatedValue = currentStepItem.querySelector('.calculated-step-value');
                calculatedDiv.style.display = 'block';
                calculatedValue.textContent = weight.toFixed(2);
            });
        }
        
        function getStepAtPosition(x, y) {
            const canvas = document.getElementById('shaftCanvas');
            const centerY = canvas.height / 2;
            const maxDiameter = Math.max(...canvasSteps.map(s => s.diameter));
            const totalLength = canvasSteps.reduce((sum, s) => sum + s.length, 0);
            
            // 计算缩放比例
            const availableWidth = canvas.width - 200;
            const availableHeight = canvas.height - 150;
            const scaleX = availableWidth / totalLength;
            const scaleY = availableHeight / maxDiameter;
            const scale = Math.min(scaleX, scaleY, 1.2);
            
            let startX = 120;
            for (let i = 0; i < canvasSteps.length; i++) {
                const step = canvasSteps[i];
                const width = step.length * scale;
                const height = step.diameter * scale;
                const stepX = startX;
                const stepY = centerY - height / 2;
                
                if (x >= stepX && x <= stepX + width && y >= stepY && y <= stepY + height) {
                    return step;
                }
                
                startX += width; // 移除间距，台阶连接在一起
            }
            return null;
        }
        
        function updateStepThirdParameter(input) {
            const stepItem = input.closest('.step-item');
            const diameterInput = stepItem.querySelector('.step-diameter');
            const lengthInput = stepItem.querySelector('.step-length');
            const weightInput = stepItem.querySelector('.step-weight-input');
            const calculatedDiv = stepItem.querySelector('.step-calculated');
            const calculatedValue = stepItem.querySelector('.calculated-step-value');
            
            const diameter = parseFloat(diameterInput.value) || 0;
            const length = parseFloat(lengthInput.value) || 0;
            const weight = parseFloat(weightInput.value) || 0;
            const density = getDensity();
            
            // 计算已输入的参数数量
            const inputs = [diameter, length, weight].filter(val => val > 0);
            
            if (inputs.length !== 2 || density <= 0) {
                calculatedDiv.style.display = 'none';
                return;
            }
            
            let result = '';
            
            // 如果缺少直径
            if (diameter <= 0 && length > 0 && weight > 0) {
                const volume = weight * 1000 / density;
                const calculatedDiameter = Math.sqrt(volume / (Math.PI * (length / 10))) * 20;
                result = `直径: ${calculatedDiameter.toFixed(1)} 毫米`;
            }
            // 如果缺少长度
            else if (diameter > 0 && length <= 0 && weight > 0) {
                const volume = weight * 1000 / density;
                const calculatedLength = volume / (Math.PI * (diameter / 20) ** 2) * 10;
                result = `长度: ${calculatedLength.toFixed(1)} 毫米`;
            }
            // 如果缺少重量
            else if (diameter > 0 && length > 0 && weight <= 0) {
                const volume = calculateVolume(diameter, length);
                const calculatedWeight = calculateWeight(volume, density);
                result = `重量: ${calculatedWeight.toFixed(2)} 千克`;
            }
            
            if (result) {
                calculatedValue.textContent = result;
                calculatedDiv.style.display = 'block';
            } else {
                calculatedDiv.style.display = 'none';
            }
        }
        
        function updateStepWeight(input) {
            const stepItem = input.closest('.step-item');
            const diameterInput = stepItem.querySelector('.step-diameter');
            const lengthInput = stepItem.querySelector('.step-length');
            const weightInput = stepItem.querySelector('.step-weight-input');
            const calculatedDiv = stepItem.querySelector('.step-calculated');
            const calculatedValue = stepItem.querySelector('.calculated-step-value');
            
            const diameter = parseFloat(diameterInput.value) || 0;
            const length = parseFloat(lengthInput.value) || 0;
            const weight = parseFloat(weightInput.value) || 0;
            const density = getDensity();
            
            // 计算已输入的参数数量
            const inputs = [diameter, length, weight].filter(val => val > 0);
            
            if (inputs.length !== 2 || density <= 0) {
                calculatedDiv.style.display = 'none';
                return;
            }
            
            let result = '';
            
            // 如果缺少直径
            if (diameter <= 0 && length > 0 && weight > 0) {
                const volume = weight * 1000 / density;
                const calculatedDiameter = Math.sqrt(volume / (Math.PI * (length / 10))) * 20;
                result = `直径: ${calculatedDiameter.toFixed(1)} 毫米`;
            }
            // 如果缺少长度
            else if (diameter > 0 && length <= 0 && weight > 0) {
                const volume = weight * 1000 / density;
                const calculatedLength = volume / (Math.PI * (diameter / 20) ** 2) * 10;
                result = `长度: ${calculatedLength.toFixed(1)} 毫米`;
            }
            // 如果缺少重量
            else if (diameter > 0 && length > 0 && weight <= 0) {
                const volume = calculateVolume(diameter, length);
                const calculatedWeight = calculateWeight(volume, density);
                result = `重量: ${calculatedWeight.toFixed(2)} 千克`;
            }
            
            if (result) {
                calculatedValue.textContent = result;
                calculatedDiv.style.display = 'block';
            } else {
                calculatedDiv.style.display = 'none';
            }
        }
        
        function calculateOriginalIngotParams(diameter, length, weight, density) {
            // 计算已输入的参数数量
            const inputs = [diameter, length, weight].filter(val => val > 0);
            
            if (inputs.length < 2 || density <= 0) {
                return null;
            }
            
            let finalDiameter = diameter;
            let finalLength = length;
            
            // 如果缺少直径，计算直径
            if (diameter <= 0 && length > 0 && weight > 0) {
                const volume = weight * 1000 / density;
                finalDiameter = Math.sqrt(volume / (Math.PI * (length / 10))) * 20;
            }
            // 如果缺少长度，计算长度
            else if (diameter > 0 && length <= 0 && weight > 0) {
                const volume = weight * 1000 / density;
                finalLength = volume / (Math.PI * (diameter / 20) ** 2) * 10;
            }
            
            return {
                diameter: finalDiameter,
                length: finalLength
            };
        }
        
        function calculateStepParams(diameter, length, weight, density) {
            // 计算已输入的参数数量
            const inputs = [diameter, length, weight].filter(val => val > 0);
            
            if (inputs.length < 2 || density <= 0) {
                return null;
            }
            
            let finalDiameter = diameter;
            let finalLength = length;
            
            // 如果缺少直径，计算直径
            if (diameter <= 0 && length > 0 && weight > 0) {
                const volume = weight * 1000 / density;
                finalDiameter = Math.sqrt(volume / (Math.PI * (length / 10))) * 20;
            }
            // 如果缺少长度，计算长度
            else if (diameter > 0 && length <= 0 && weight > 0) {
                const volume = weight * 1000 / density;
                finalLength = volume / (Math.PI * (diameter / 20) ** 2) * 10;
            }
            
            return {
                diameter: finalDiameter,
                length: finalLength
            };
        }
        
        function calculateThirdParameter() {
            const diameter = parseFloat(document.getElementById('originalDiameter').value) || 0;
            const length = parseFloat(document.getElementById('originalLength').value) || 0;
            const weight = parseFloat(document.getElementById('originalWeight').value) || 0;
            const density = getDensity();
            const calculatedDiv = document.getElementById('calculatedParameter');
            const calculatedValue = document.getElementById('calculatedValue');
            
            // 计算已输入的参数数量
            const inputs = [diameter, length, weight].filter(val => val > 0);
            
            if (inputs.length !== 2 || density <= 0) {
                calculatedDiv.style.display = 'none';
                return;
            }
            
            let result = '';
            
            // 如果缺少直径
            if (diameter <= 0 && length > 0 && weight > 0) {
                const volume = weight * 1000 / density; // 转换为立方厘米
                const calculatedDiameter = Math.sqrt(volume / (Math.PI * (length / 10))) * 20; // 转换为毫米
                result = `直径: ${calculatedDiameter.toFixed(1)} 毫米`;
            }
            // 如果缺少长度
            else if (diameter > 0 && length <= 0 && weight > 0) {
                const volume = weight * 1000 / density; // 转换为立方厘米
                const calculatedLength = volume / (Math.PI * (diameter / 20) ** 2) * 10; // 转换为毫米
                result = `长度: ${calculatedLength.toFixed(1)} 毫米`;
            }
            // 如果缺少重量
            else if (diameter > 0 && length > 0 && weight <= 0) {
                const volume = calculateVolume(diameter, length);
                const calculatedWeight = calculateWeight(volume, density);
                result = `重量: ${calculatedWeight.toFixed(2)} 千克`;
            }
            
            if (result) {
                calculatedValue.textContent = result;
                calculatedDiv.style.display = 'block';
            } else {
                calculatedDiv.style.display = 'none';
            }
        }
        
        function updateOriginalWeight() {
            const diameter = parseFloat(document.getElementById('originalDiameter').value);
            const length = parseFloat(document.getElementById('originalLength').value);
            const density = getDensity();
            
            if (diameter > 0 && length > 0 && density > 0) {
                calculateThirdParameter();
            }
        }
        
        function updateAllStepWeights() {
            const stepItems = document.querySelectorAll('.step-item');
            stepItems.forEach(stepItem => {
                const diameterInput = stepItem.querySelector('.step-diameter');
                const lengthInput = stepItem.querySelector('.step-length');
                const weightInput = stepItem.querySelector('.step-weight-input');
                
                if (diameterInput.value || lengthInput.value || weightInput.value) {
                    updateStepThirdParameter(diameterInput);
                }
            });
        }
        
        function updateDensity() {
            const select = document.getElementById('materialDensity');
            const customInput = document.getElementById('customDensity');
            
            if (select.value === 'custom') {
                customInput.style.display = 'block';
                customInput.focus();
            } else {
                customInput.style.display = 'none';
            }
        }
        
        function getDensity() {
            const select = document.getElementById('materialDensity');
            const customInput = document.getElementById('customDensity');
            
            if (select.value === 'custom') {
                return parseFloat(customInput.value);
            } else {
                return parseFloat(select.value);
            }
        }
        
        function calculateVolume(diameter, length) {
            // 计算圆柱体体积 (立方厘米)
            const radius = diameter / 20; // 转换为厘米
            const lengthCm = length / 10; // 转换为厘米
            return Math.PI * radius * radius * lengthCm;
        }
        
        function calculateWeight(volume, density) {
            // 计算重量 (千克)
            return (volume * density) / 1000;
        }
        
        function calculate() {
            // 获取输入值
            const d0Input = parseFloat(document.getElementById('originalDiameter').value) || 0;
            const L0Input = parseFloat(document.getElementById('originalLength').value) || 0;
            const weightInput = parseFloat(document.getElementById('originalWeight').value) || 0;
            const density = getDensity();
            
            if (!density || density <= 0) {
                alert('请输入有效的材料密度！');
                return;
            }
            
            // 计算原始钢锭的完整参数
            const originalParams = calculateOriginalIngotParams(d0Input, L0Input, weightInput, density);
            if (!originalParams) {
                alert('请至少输入原始钢锭的两个参数（直径、长度、重量）！');
                return;
            }
            
            const d0 = originalParams.diameter;
            const L0 = originalParams.length;
            
            // 获取台阶参数
            const steps = [];
            
            if (currentInputMode === 'visual') {
                // 可视化模式：从画布数据获取
                if (canvasSteps.length === 0) {
                    alert('请至少添加一个台阶！');
                    return;
                }
                
                canvasSteps.forEach((step, index) => {
                    steps.push({
                        diameter: step.diameter,
                        length: step.length,
                        index: index + 1
                    });
                });
            } else {
                // 表格模式：从输入框获取
                const stepItems = document.querySelectorAll('.step-item');
                
                for (let i = 0; i < stepItems.length; i++) {
                    const diameter = parseFloat(stepItems[i].querySelector('.step-diameter').value) || 0;
                    const length = parseFloat(stepItems[i].querySelector('.step-length').value) || 0;
                    const weight = parseFloat(stepItems[i].querySelector('.step-weight-input').value) || 0;
                    
                    // 计算台阶的完整参数
                    const stepParams = calculateStepParams(diameter, length, weight, density);
                    if (!stepParams) {
                        alert(`台阶 ${i + 1} 请至少输入两个参数（直径、长度、重量）！`);
                        return;
                    }
                    
                    steps.push({
                        diameter: stepParams.diameter,
                        length: stepParams.length,
                        index: i + 1
                    });
                }
            }
            
            if (steps.length === 0) {
                alert('请至少添加一个台阶！');
                return;
            }
            
            // 计算结果
            let totalOriginalLength = 0;
            let currentPosition = 0;
            let totalWeight = 0;
            const results = [];
            
            for (const step of steps) {
                const li = step.length * Math.pow(step.diameter / d0, 2);
                const volume = calculateVolume(step.diameter, step.length);
                const weight = calculateWeight(volume, density);
                
                results.push({
                    ...step,
                    originalLength: li,
                    startPosition: currentPosition,
                    endPosition: currentPosition + li,
                    volume: volume,
                    weight: weight
                });
                totalOriginalLength += li;
                totalWeight += weight;
                currentPosition += li;
            }
            
            // 保存当前结果
            currentResults = {
                results: results,
                totalLength: totalOriginalLength,
                L0: L0,
                d0: d0,
                totalWeight: totalWeight,
                density: density,
                timestamp: new Date().toLocaleString()
            };
            
            // 显示结果
            displayResults(results, totalOriginalLength, L0, d0, totalWeight, density);
            
            // 如果当前是可视化模式，更新画布
            if (currentInputMode === 'visual') {
                // 将计算结果同步到画布
                canvasSteps = [];
                results.forEach((result, index) => {
                    canvasSteps.push({
                        id: Date.now() + index,
                        diameter: result.diameter,
                        length: result.length,
                        color: getRandomColor()
                    });
                });
                updateCanvasStepsList();
                drawAllSteps();
            }
        }
        
        function displayResults(results, totalLength, L0, d0, totalWeight, density) {
            const resultsDiv = document.getElementById('results');
            const contentDiv = document.getElementById('resultContent');
            
            let html = `
                <table class="result-table">
                    <thead>
                        <tr>
                            <th>台阶</th>
                            <th>最终直径</th>
                            <th>最终长度</th>
                            <th>原始长度</th>
                            <th>起始位置</th>
                            <th>体积</th>
                            <th>重量</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            for (const result of results) {
                html += `
                    <tr>
                        <td>${result.index}</td>
                        <td>${result.diameter.toFixed(1)}</td>
                        <td>${result.length.toFixed(1)}</td>
                        <td>${result.originalLength.toFixed(1)}</td>
                        <td>${result.startPosition.toFixed(1)}</td>
                        <td>${result.volume.toFixed(1)} cm³</td>
                        <td>${result.weight.toFixed(2)} kg</td>
                    </tr>
                `;
            }
            
            html += `
                    </tbody>
                </table>
                
                <div style="margin: 16px 0; padding: 16px; background: #f8f9fa; border-radius: 8px; border: 1px solid #e0e0e0;">
                    <strong>原始钢锭直径:</strong> ${d0.toFixed(1)} 毫米<br>
                    <strong>原始钢锭长度:</strong> ${L0.toFixed(1)} 毫米<br>
                    <strong>原始钢锭重量:</strong> ${(calculateWeight(calculateVolume(d0, L0), density)).toFixed(2)} kg<br>
                    <strong>材料密度:</strong> ${density.toFixed(2)} g/cm³<br>
                    <strong>总需要长度:</strong> ${totalLength.toFixed(1)} 毫米<br>
                    <strong>台阶轴总重量:</strong> ${totalWeight.toFixed(2)} kg<br>
                    <strong>材料利用率:</strong> ${((totalWeight / calculateWeight(calculateVolume(d0, L0), density)) * 100).toFixed(1)}%
                </div>
            `;
            
            if (totalLength <= L0) {
                html += `
                    <div class="success">
                        可行！钢锭长度足够。<br>
                        剩余长度: ${(L0 - totalLength).toFixed(1)} 毫米
                    </div>
                    
                    <div class="plan">
                        <h4>锻造计划</h4>
                        <p>建议按以下方式划分钢锭：</p>
                `;
                
                for (const result of results) {
                    html += `
                        <p>第${result.index}个台阶: 从 ${result.startPosition.toFixed(1)} 毫米到 ${result.endPosition.toFixed(1)} 毫米</p>
                    `;
                }
                
                html += `</div>`;
            } else {
                const shortage = totalLength - L0;
                html += `
                    <div class="error">
                        不可行！钢锭长度不足。<br>
                        需要额外长度: ${shortage.toFixed(1)} 毫米
                    </div>
                    
                    <div class="plan">
                        <h4>建议</h4>
                        <p>1. 增加原始钢锭长度至 ${(L0 + shortage).toFixed(1)} 毫米</p>
                        <p>2. 或减少台阶轴的总长度</p>
                        <p>3. 或调整台阶尺寸</p>
                    </div>
                `;
            }
            
            contentDiv.innerHTML = html;
            resultsDiv.classList.add('show');
            
            // 滚动到结果区域
            resultsDiv.scrollIntoView({ behavior: 'smooth' });
        }
        
        function saveToHistory() {
            if (!currentResults) {
                alert('请先进行计算！');
                return;
            }
            
            const historyItem = {
                ...currentResults,
                id: Date.now(),
                name: `计算记录 ${historyData.length + 1}`
            };
            
            historyData.unshift(historyItem); // 添加到开头
            
            // 限制历史记录数量（最多保存20条）
            if (historyData.length > 20) {
                historyData = historyData.slice(0, 20);
            }
            
            saveHistoryToStorage();
            displayHistory();
            
            alert('已保存到历史记录！');
        }
        
        function loadHistory() {
            const saved = localStorage.getItem('forgingHistory');
            if (saved) {
                try {
                    historyData = JSON.parse(saved);
                    displayHistory();
                } catch (e) {
                    console.error('加载历史记录失败:', e);
                    historyData = [];
                }
            }
        }
        
        function saveHistoryToStorage() {
            try {
                localStorage.setItem('forgingHistory', JSON.stringify(historyData));
            } catch (e) {
                console.error('保存历史记录失败:', e);
            }
        }
        
        function displayHistory() {
            const historyList = document.getElementById('historyList');
            
            if (historyData.length === 0) {
                historyList.innerHTML = '<p style="color: #666; text-align: center; padding: 20px;">暂无历史记录</p>';
                return;
            }
            
            let html = '';
            historyData.forEach((item, index) => {
                const isFeasible = item.totalLength <= item.L0;
                const status = isFeasible ? '可行' : '不可行';
                const statusColor = isFeasible ? '#27ae60' : '#e74c3c';
                
                html += `
                    <div class="history-item" style="background: white; border: 1px solid #e0e0e0; border-radius: 8px; padding: 16px; margin-bottom: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.05);">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                            <h4 style="margin: 0; color: #2c3e50;">${item.name}</h4>
                            <div style="display: flex; gap: 8px;">
                                <button onclick="loadFromHistory(${item.id})" style="background: #3498db; color: white; border: none; border-radius: 4px; padding: 4px 8px; font-size: 12px; cursor: pointer;">加载</button>
                                <button onclick="deleteHistory(${item.id})" style="background: #e74c3c; color: white; border: none; border-radius: 4px; padding: 4px 8px; font-size: 12px; cursor: pointer;">删除</button>
                            </div>
                        </div>
                        <div style="font-size: 14px; color: #666; margin-bottom: 8px;">
                            <span>原始钢锭: ${item.d0}×${item.L0}mm</span> | 
                            <span>密度: ${item.density} g/cm³</span> | 
                            <span>台阶数: ${item.results.length}</span> | 
                            <span>总重量: ${item.totalWeight.toFixed(2)} kg</span>
                        </div>
                        <div style="font-size: 14px; color: #666;">
                            <span style="color: ${statusColor}; font-weight: 500;">状态: ${status}</span> | 
                            <span>时间: ${item.timestamp}</span>
                        </div>
                    </div>
                `;
            });
            
            historyList.innerHTML = html;
        }
        
        function loadFromHistory(id) {
            const item = historyData.find(h => h.id === id);
            if (!item) return;
            
            // 填充原始钢锭参数
            document.getElementById('originalDiameter').value = item.d0;
            document.getElementById('originalLength').value = item.L0;
            document.getElementById('originalWeight').value = ''; // 清空重量，让它自动计算
            
            // 填充材料密度
            const densitySelect = document.getElementById('materialDensity');
            const customDensity = document.getElementById('customDensity');
            
            // 检查是否是预设密度
            const presetDensities = ['7.85', '7.9', '8.0', '2.7', '8.9'];
            if (presetDensities.includes(item.density.toString())) {
                densitySelect.value = item.density;
                customDensity.style.display = 'none';
            } else {
                densitySelect.value = 'custom';
                customDensity.style.display = 'block';
                customDensity.value = item.density;
            }
            
            // 清空现有台阶
            document.getElementById('stepsContainer').innerHTML = '';
            stepCount = 0;
            
            // 添加历史台阶
            item.results.forEach(result => {
                addStep();
                const lastStep = document.querySelector('.step-item:last-child');
                lastStep.querySelector('.step-diameter').value = result.diameter;
                lastStep.querySelector('.step-length').value = result.length;
                lastStep.querySelector('.step-weight-input').value = ''; // 清空重量，让它自动计算
                updateStepThirdParameter(lastStep.querySelector('.step-diameter'));
            });
            
            // 重新计算
            calculate();
            
            alert('已加载历史记录！');
        }
        
        function deleteHistory(id) {
            if (confirm('确定要删除这条历史记录吗？')) {
                historyData = historyData.filter(h => h.id !== id);
                saveHistoryToStorage();
                displayHistory();
            }
        }
    </script>
</body>
</html> 